// semaphore_demo.c
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

sem_t sem;
int shared_value = 0;

void* thread1(void* arg) {
    while (shared_value < 10) {
        sem_wait(&sem);
        shared_value++;
        printf("Thread1: shared_value = %d\n", shared_value);
        sem_post(&sem);
        sleep(1);
    }
    return NULL;
}

void* thread2(void* arg) {
    while (shared_value < 10) {
        sem_wait(&sem);
        shared_value *= 2;
        printf("Thread2: shared_value = %d\n", shared_value);
        sem_post(&sem);
        sleep(1);
    }
    return NULL;
}

int main() {
    pthread_t tid1, tid2;
    sem_init(&sem, 0, 1);

    pthread_create(&tid1, NULL, thread1, NULL);
    pthread_create(&tid2, NULL, thread2, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    sem_destroy(&sem);
    return 0;
}
